#define _CRT_SECURE_NO_WARNINGS

#include"List.h"

LTNode* BuyListNode(LTDataType x)
{
	LTNode* node = (LTNode*)malloc(sizeof(LTNode));
	if (node == NULL)
	{
		perror("malloc fail");
		return NULL;
	}

	node->data = x;
	node->next = NULL;
	node->prev = NULL;
	return node;
}

LTNode* ListInit()
{
	LTNode* phead = BuyListNode(1);
	phead->next = phead;
	phead->prev = phead;

	return phead;
}



void ListPrint(LTNode* phead)
{
	assert(phead);

	LTNode* cur = phead->next;
	while (cur != phead)
	{
		printf("%d ", cur->data);
		cur = cur->next;
	}
	printf("\n");
}



void ListPushBack(LTNode* phead, LTDataType x)
{
	assert(phead);

	/*LTNode* newnode = BuyListNode(x);
	LTNode* tail = phead->prev;
	tail->next = newnode;
	newnode->next = phead;
	newnode->prev = tail;
	phead->prev = newnode;*/

	ListInsert(phead->prev, x);
}



void ListPushFront(LTNode* phead, LTDataType x)
{
	assert(phead);

	/*LTNode* newnode = BuyListNode(x);
	LTNode* tail = phead->next;
	phead->next = newnode;
	newnode->next = tail;
	newnode->prev = phead;
	tail->prev = newnode;*/

	ListInsert(phead->next, x);
}



void ListPopBack(LTNode* phead)
{
	assert(phead);
	assert(phead->next != phead);


	/*LTNode* tail = phead->prev;
	LTNode* tailPrev = tail->prev;

	free(tail);

	phead->prev = tailPrev;
	tailPrev->next = phead;*/

	ListErase(phead->prev);
}



void ListPopFront(LTNode* phead)
{
	assert(phead);
	assert(phead->next != phead);

	/*LTNode* tail = phead->next;
	LTNode* tailNext = tail->next;

	free(tail);

	phead->next = tailNext;
	tailNext->prev = phead;*/

	ListErase(phead->next);
}



void ListInsert(LTNode* pos, LTDataType x)
{
	assert(pos);

	LTNode* prev = pos->prev;
	LTNode* newnode = BuyListNode(x);

	prev->next = newnode;
	newnode->next = pos;
	pos->prev = newnode;
	newnode->prev = prev;

}



void ListErase(LTNode* pos)
{
	assert(pos);

	LTNode* prev = pos->prev;
	LTNode* next = pos->next;

	prev->next = next;
	next->prev = prev;
	free(pos);
}


LTNode* ListFind(LTNode* phead, LTDataType x)
{
	LTNode* cur = phead;
	while (cur)
	{
		if (cur->data == x)
			return cur;
		cur = cur->next;
	}

	return NULL;
}